package com.ysucloud.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysucloud.manager.VO.ResultListVO;
import com.ysucloud.manager.VO.ResultObjectVO;
import com.ysucloud.manager.dataobject.ProductCategory;
import com.ysucloud.manager.exception.NullParameterException;
import com.ysucloud.manager.server.ProductCategoryServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 主要实现业务的增删改查
 *
 * Description: manager
 * Created by 刘翰文 on 2019/6/27 13:23
 *
 */
@RestController
@RequestMapping("/type")
public class ProductCategoryController {
    @Autowired
    ProductCategoryServer productCategoryServer;

    /** 查询全体类目信息 */
    @PostMapping("/get")
    public ResultListVO findAll(){
        List<ProductCategory> list = productCategoryServer.getAllProductCategory();

        ResultListVO result = new ResultListVO();
        result.setData(list);

        return result;
    }

    /** 新增 */
    @PostMapping("/save")
    public ResultObjectVO save(@RequestBody JSONObject jsonObject){
        if(jsonObject.getString("name") == null){
            throw new NullParameterException();
        }

        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryName(jsonObject.getString("name"));

        ResultObjectVO result = new ResultObjectVO();

        if(!productCategoryServer.saveProductCategory(productCategory)){
            result.setCode(10000);
            result.setMsg("数据库异常！");
        }

        return result;
    }

    /** 修改 */
    @PostMapping("/change")
    public ResultObjectVO change(@RequestBody JSONObject jsonObject){
        if(jsonObject.getString("name") == null
        || jsonObject.getInteger("id") == null)
        {
            throw new NullParameterException();
        }
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryId(jsonObject.getInteger("id"));
        productCategory.setCategoryName(jsonObject.getString("name"));

        ResultObjectVO result = new ResultObjectVO();

        productCategoryServer.changeProductCategory(productCategory);


        return result;
    }

    /** 删除 */
    @PostMapping("/delete")
    public ResultObjectVO delete(@RequestBody JSONObject jsonObject){
        if(jsonObject.getInteger("id") == null){
            throw new NullParameterException();
        }

        productCategoryServer.deleteProductCategory(jsonObject.getInteger("id"));

        ResultObjectVO result = new ResultObjectVO();

        return result;
    }

}
